/* eslint-disable no-console */
/* eslint-disable unicorn/no-process-exit */
/* eslint-disable n/prefer-global/process */
import fs from 'node:fs';
import path from 'node:path';
import readline from 'node:readline';

// Check if input_file is set
if (process.argv.length < 3) {
  console.error('Error: No input file specified.');
  console.log('Usage: node db_csv_extractor.js <input_file> [output_dir]');
  process.exit(1);
}

const inputFile = process.argv[2];
const outputDir = process.argv[3] || './output';

// Create output directory
if (!fs.existsSync(outputDir)) {
  fs.mkdirSync(outputDir, { recursive: true });
}

let currentSection = '';
let currentContent = '';

const rl = readline.createInterface({
  crlfDelay: Infinity,
  input: fs.createReadStream(inputFile),
});

rl.on('line', (line) => {
  const startMatch = line.match(/^START_(\w+)/);
  const endMatch = line.match(/^END_(\w+)$/);

  if (startMatch) {
    if (currentSection) {
      // Save the previous SECTION content
      fs.writeFileSync(
        path.join(outputDir, `${currentSection}.csv`),
        currentContent,
      );
    }
    currentSection = startMatch[1];
    currentContent = '';
  } else if (endMatch) {
    if (currentSection === endMatch[1]) {
      // End the current SECTION, save content
      fs.writeFileSync(
        path.join(outputDir, `${currentSection}.csv`),
        currentContent,
      );
      currentSection = '';
      currentContent = '';
    } else {
      console.warn(`Warning: Mismatched END_ section for ${currentSection}`);
    }
  } else {
    // Append the current line to the current SECTION content
    if (currentContent) {
      currentContent += `\n${line}`;
    } else {
      currentContent = line;
    }
  }
});

rl.on('close', () => {
  // Process the last SECTION
  if (currentSection) {
    fs.writeFileSync(
      path.join(outputDir, `${currentSection}.csv`),
      currentContent,
    );
  }
  console.log(`CSV files generated successfully in ${outputDir}.`);
});
